/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar;

import java.io.File;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Runtime
{
	private static final Logger logger = LogManager.getLogger();

	public static final int SECL_HIGH = 1;
	public static final int SECL_MID  = 2;
	public static final int SECL_LOW  = 3;

	private static String runt_base = null;
	private static int runt_secl = 0;
	private static String runt_diagnose = null;
	private static String notify_sender = "?";

	static {
		secureLevel();
	}

	/**
	 * 获取运行时安全级别
	 */
	public static int secureLevel() {
		if (runt_secl == 0) {
			String secl = System.getProperty("RUNT.SECL");
			if (secl == null) {
				logger.error("没有定义系统变量[RUNT.SECL]，默认采用最高安全级别.");
				runt_secl = SECL_HIGH;
			} else {
				try {
					runt_secl = Integer.parseInt(secl);
				} catch (NumberFormatException e) {
					logger.warn("RUNT.SECL 的值[{}]不是一个有效的数字.", secl);
					runt_secl = SECL_HIGH;
				}
			}
		}
		if (runt_secl < SECL_HIGH || runt_secl > SECL_LOW) {
			logger.warn("RUNT.SECL 的值[{}]不是一个有效的数字", runt_secl);
			runt_secl = SECL_HIGH;
		}
		return runt_secl;
	}

	/**
	 * 获取运行时基本路径
	 */
	public static String basePath() {
		if (runt_base == null) {
			runt_base = System.getProperty("RUNT.BASE");
			if (runt_base == null) {
				logger.error("没有定义系统变量[RUNT.BASE]，"
						+ "请在启动时使用 Java 命令选项[-DRUNT.BASE=...].");
				return null;
			}
			File file = new File(runt_base);
			if (!file.isDirectory()) {
				logger.error("[RUNT.BASE]设置有误，[{}]不是一个目录.", runt_base);
				runt_base = null;
				return null;
			}
		}
		return runt_base;
	}

	/**
	 * 相对运行时基本路径寻找一个子路径
	 */
	public static String pathFor(String subpath) {
		String path = basePath();
		return path == null ? null : path + subpath;
	}

	/**
	 * 获取运行时基本路径，以 File 方式返回
	 */
	public static File baseFile() {
		String path = basePath();
		return path == null ? null : new File(path);
	}

	/**
	 * 相对运行时基本路径寻找一个子路径，以 File 方式返回
	 */
	public static File fileFor(String subpath) {
		String path = pathFor(subpath);
		return path == null ? null : new File(path);
	}

	/**
	 * 设置通知发起者
	 */
	public static void setNotifySender(String sender) {
		notify_sender = sender;
	}

	public static String getNotifySender() {
		return notify_sender;
	}

	public static boolean diagnoseEnabled() {
		if (runt_diagnose == null) {
			runt_diagnose = System.getProperty("RUNT.DIAGNOSE");
			if (runt_diagnose == null) {
				return true;
			}
		}
		return Boolean.parseBoolean(runt_diagnose);
	}

}
